package com.itheima.easy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itheima.easy.constant.UserCacheConstant;
import com.itheima.easy.service.LogoutService;
import com.itheima.easy.utils.UserThreadLocal;
import com.itheima.easy.vo.UserVo;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName LoginFacedImpl.java
 * @Description 退出接口实现
 */
@Component
public class LogoutServiceImpl implements LogoutService {

    @Autowired
    RedissonClient redissonClient;

    @Override
    public Boolean logout() {
        String subject = UserThreadLocal.getSubject();
        UserVo userVo = JSONObject.parseObject(subject,UserVo.class);
        //移除缓存：用户关联userToken
        String userTokenKey = UserCacheConstant.USER_TOKEN+userVo.getUsername();
        RBucket<String> userTokenBucket = redissonClient.getBucket(userTokenKey);
        boolean isDelete = userTokenBucket.delete();
        if (!isDelete){
            throw new RuntimeException("退出失败！");
        }
        //语出缓存：userToken关联jwtToken
        String jwtTokenKey = UserCacheConstant.JWT_TOKEN+userVo.getUserToken();
        RBucket<String> jwtTokenKeyBucket = redissonClient.getBucket(jwtTokenKey);
        isDelete = jwtTokenKeyBucket.delete();
        if (!isDelete){
            throw new RuntimeException("退出失败！");
        }
        return isDelete;
    }
}
